import { MockMethod } from 'vite-plugin-mock'
import { UserStatus, MenuType } from '../../src/model/user-role-model'
import type { Permission as ApiPermission } from '../../src/request/auth-api'

// We'll use the ApiPermission interface directly from auth-api.ts

// 用户数据
const users = [
  {
    id: 1,
    login_name: 'admin',
    full_name: '系统管理员',
    role_id: 1,
    role_name: '超级管理员',
    status: UserStatus.ACTIVE,
    department: '管理部',
    created_at: '2025-08-07T02:55:11',
    updated_at: '2025-08-07T02:55:11'
  },
  {
    id: 2,
    login_name: 'test_user',
    full_name: '测试用户',
    role_id: 2,
    role_name: '普通用户',
    status: UserStatus.ACTIVE,
    department: '测试部',
    created_at: '2025-08-07T11:40:00',
    updated_at: '2025-08-07T11:41:30'
  },
  {
    id: 3,
    login_name: 'dev_user',
    full_name: '开发人员',
    role_id: 3,
    role_name: '开发人员',
    status: UserStatus.ACTIVE,
    department: '研发部',
    created_at: '2025-08-07T11:42:15',
    updated_at: '2025-08-07T11:42:15'
  }
]

// 角色数据
const roles = [
  {
    id: 1,
    name: '超级管理员',
    description: '系统超级管理员，拥有所有权限',
    created_at: '2025-08-07T02:55:11',
    updated_at: '2025-08-07T02:55:11',
    permissions: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 20, 21, 22, 23, 24, 25, 26, 27],
    permission_ids: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 20, 21, 22, 23, 24, 25, 26, 27, 30, 40, 41, 42, 50, 51],
    permission_count: 31
  },
  {
    id: 2,
    name: '普通用户',
    description: '普通用户，拥有基本权限',
    created_at: '2025-08-07T02:55:11',
    updated_at: '2025-08-07T02:55:11',
    permissions: [2, 24],
    permission_ids: [2, 24, 30],
    permission_count: 3
  },
  {
    id: 3,
    name: '开发人员',
    description: '开发团队成员',
    created_at: '2025-08-07T11:42:15',
    updated_at: '2025-08-07T11:42:15',
    permissions: [1, 2, 3, 6, 10, 20, 24, 25, 26],
    permission_ids: [1, 2, 3, 6, 10, 20, 24, 25, 26, 30],
    permission_count: 10
  }
]

// 权限数据（扁平结构）
const permissions = [
  // 系统管理
  {
    id: 1,
    name: '系统管理',
    url: null,
    method: null,
    parent_id: null,
    level: 1,
    order: 1,
    icon: 'setting',
    is_menu: MenuType.MENU,
    created_at: '2025-08-07T02:55:11',
    updated_at: '2025-08-07T02:55:11'
  },
  
  // 用户管理
  {
    id: 2,
    name: '用户管理',
    url: '/users',
    method: 'GET',
    parent_id: 1,
    level: 2,
    order: 1,
    icon: 'user',
    is_menu: MenuType.MENU,
    created_at: '2025-08-07T02:55:11',
    updated_at: '2025-08-07T02:55:11'
  },
  {
    id: 3,
    name: '创建用户',
    url: '/users',
    method: 'POST',
    parent_id: 2,
    level: 2,
    order: 1,
    icon: null,
    is_menu: MenuType.BUTTON,
    created_at: '2025-08-07T02:55:11',
    updated_at: '2025-08-07T02:55:11'
  },
  {
    id: 4,
    name: '修改用户',
    url: '/users/:id',
    method: 'PUT',
    parent_id: 2,
    level: 2,
    order: 2,
    icon: null,
    is_menu: MenuType.BUTTON,
    created_at: '2025-08-07T02:55:11',
    updated_at: '2025-08-07T02:55:11'
  },
  {
    id: 5,
    name: '删除用户',
    url: '/users/:id',
    method: 'DELETE',
    parent_id: 2,
    level: 2,
    order: 3,
    icon: null,
    is_menu: MenuType.BUTTON,
    created_at: '2025-08-07T02:55:11',
    updated_at: '2025-08-07T02:55:11'
  },
  {
    id: 11,
    name: '导出用户',
    url: '/users/export',
    method: 'GET',
    parent_id: 2,
    level: 2,
    order: 4,
    icon: null,
    is_menu: MenuType.BUTTON,
    created_at: '2025-08-07T11:43:20',
    updated_at: '2025-08-07T11:43:20'
  },
  {
    id: 12,
    name: '重置用户密码',
    url: '/users/:id/reset-password',
    method: 'POST',
    parent_id: 2,
    level: 2,
    order: 5,
    icon: null,
    is_menu: MenuType.BUTTON,
    created_at: '2025-08-07T11:44:20',
    updated_at: '2025-08-07T11:44:20'
  },
  {
    id: 13,
    name: '修改用户密码',
    url: '/users/:id/change-password',
    method: 'POST',
    parent_id: 2,
    level: 2,
    order: 6,
    icon: null,
    is_menu: MenuType.BUTTON,
    created_at: '2025-08-07T11:45:20',
    updated_at: '2025-08-07T11:45:20'
  },
  
  // 角色管理
  {
    id: 6,
    name: '角色管理',
    url: '/roles',
    method: 'GET',
    parent_id: 1,
    level: 2,
    order: 2,
    icon: 'team',
    is_menu: MenuType.MENU,
    created_at: '2025-08-07T02:55:11',
    updated_at: '2025-08-07T02:55:11'
  },
  {
    id: 7,
    name: '创建角色',
    url: '/roles',
    method: 'POST',
    parent_id: 6,
    level: 2,
    order: 1,
    icon: null,
    is_menu: MenuType.BUTTON,
    created_at: '2025-08-07T02:55:11',
    updated_at: '2025-08-07T02:55:11'
  },
  {
    id: 8,
    name: '修改角色',
    url: '/roles/:id',
    method: 'PUT',
    parent_id: 6,
    level: 2,
    order: 2,
    icon: null,
    is_menu: MenuType.BUTTON,
    created_at: '2025-08-07T02:55:11',
    updated_at: '2025-08-07T02:55:11'
  },
  {
    id: 9,
    name: '删除角色',
    url: '/roles/:id',
    method: 'DELETE',
    parent_id: 6,
    level: 2,
    order: 3,
    icon: null,
    is_menu: MenuType.BUTTON,
    created_at: '2025-08-07T02:55:11',
    updated_at: '2025-08-07T02:55:11'
  },
  
  // 权限管理
  {
    id: 10,
    name: '权限管理',
    url: '/permissions',
    method: 'GET',
    parent_id: 1,
    level: 2,
    order: 3,
    icon: 'safety',
    is_menu: MenuType.MENU,
    created_at: '2025-08-07T02:55:11',
    updated_at: '2025-08-07T02:55:11'
  },
  {
    id: 14,
    name: '创建权限',
    url: '/permissions',
    method: 'POST',
    parent_id: 10,
    level: 2,
    order: 1,
    icon: null,
    is_menu: MenuType.BUTTON,
    created_at: '2025-08-07T11:46:20',
    updated_at: '2025-08-07T11:46:20'
  },
  {
    id: 15,
    name: '修改权限',
    url: '/permissions/:id',
    method: 'PUT',
    parent_id: 10,
    level: 2,
    order: 2,
    icon: null,
    is_menu: MenuType.BUTTON,
    created_at: '2025-08-07T11:47:20',
    updated_at: '2025-08-07T11:47:20'
  },
  {
    id: 16,
    name: '删除权限',
    url: '/permissions/:id',
    method: 'DELETE',
    parent_id: 10,
    level: 2,
    order: 3,
    icon: null,
    is_menu: MenuType.BUTTON,
    created_at: '2025-08-07T11:48:20',
    updated_at: '2025-08-07T11:48:20'
  },
  {
    id: 17,
    name: '获取权限树',
    url: '/permissions/tree',
    method: 'GET',
    parent_id: 10,
    level: 2,
    order: 4,
    icon: null,
    is_menu: MenuType.BUTTON,
    created_at: '2025-08-07T11:49:20',
    updated_at: '2025-08-07T11:49:20'
  },
  
  // 服务器管理
  {
    id: 20,
    name: '服务器管理',
    url: '/servers',
    method: 'GET',
    parent_id: 1,
    level: 2,
    order: 4,
    icon: 'server',
    is_menu: MenuType.MENU,
    created_at: '2025-08-07T11:50:20',
    updated_at: '2025-08-07T11:50:20'
  },
  {
    id: 21,
    name: '创建服务器',
    url: '/servers',
    method: 'POST',
    parent_id: 20,
    level: 2,
    order: 1,
    icon: null,
    is_menu: MenuType.BUTTON,
    created_at: '2025-08-07T11:51:20',
    updated_at: '2025-08-07T11:51:20'
  },
  {
    id: 22,
    name: '修改服务器',
    url: '/servers/:id',
    method: 'PUT',
    parent_id: 20,
    level: 2,
    order: 2,
    icon: null,
    is_menu: MenuType.BUTTON,
    created_at: '2025-08-07T11:52:20',
    updated_at: '2025-08-07T11:52:20'
  },
  {
    id: 23,
    name: '删除服务器',
    url: '/servers/:id',
    method: 'DELETE',
    parent_id: 20,
    level: 2,
    order: 3,
    icon: null,
    is_menu: MenuType.BUTTON,
    created_at: '2025-08-07T11:53:20',
    updated_at: '2025-08-07T11:53:20'
  },
  
  // 部署管理
  {
    id: 24,
    name: '部署管理',
    url: '/deploy',
    method: 'GET',
    parent_id: 1,
    level: 2,
    order: 5,
    icon: 'upload',
    is_menu: MenuType.MENU,
    created_at: '2025-08-07T12:00:20',
    updated_at: '2025-08-07T12:00:20'
  },
  {
    id: 25,
    name: '创建部署',
    url: '/deploy',
    method: 'POST',
    parent_id: 24,
    level: 2,
    order: 1,
    icon: null,
    is_menu: MenuType.BUTTON,
    created_at: '2025-08-07T12:01:20',
    updated_at: '2025-08-07T12:01:20'
  },
  {
    id: 26,
    name: '修改部署',
    url: '/deploy/:id',
    method: 'PUT',
    parent_id: 24,
    level: 2,
    order: 2,
    icon: null,
    is_menu: MenuType.BUTTON,
    created_at: '2025-08-07T12:02:20',
    updated_at: '2025-08-07T12:02:20'
  },
  {
    id: 27,
    name: '删除部署',
    url: '/deploy/:id',
    method: 'DELETE',
    parent_id: 24,
    level: 2,
    order: 3,
    icon: null,
    is_menu: MenuType.BUTTON,
    created_at: '2025-08-07T12:03:20',
    updated_at: '2025-08-07T12:03:20'
  },
  
  // 仪表盘
  {
    id: 30,
    name: '仪表盘',
    url: '/dashboard',
    method: 'GET',
    parent_id: null,
    level: 1,
    order: 0,
    icon: 'dashboard',
    is_menu: MenuType.MENU,
    created_at: '2025-08-07T11:54:20',
    updated_at: '2025-08-07T11:54:20'
  },
  
  // 日志管理
  {
    id: 40,
    name: '日志管理',
    url: '/logs',
    method: 'GET',
    parent_id: 1,
    level: 2,
    order: 5,
    icon: 'document',
    is_menu: MenuType.MENU,
    created_at: '2025-08-07T11:55:20',
    updated_at: '2025-08-07T11:55:20'
  },
  {
    id: 41,
    name: '操作日志查询',
    url: '/logs/operations',
    method: 'GET',
    parent_id: 40,
    level: 2,
    order: 1,
    icon: null,
    is_menu: MenuType.BUTTON,
    created_at: '2025-08-07T11:56:20',
    updated_at: '2025-08-07T11:56:20'
  },
  {
    id: 42,
    name: '系统日志查询',
    url: '/logs/system',
    method: 'GET',
    parent_id: 40,
    level: 2,
    order: 2,
    icon: null,
    is_menu: MenuType.BUTTON,
    created_at: '2025-08-07T11:57:20',
    updated_at: '2025-08-07T11:57:20'
  },
  
  // 配置管理
  {
    id: 50,
    name: '配置管理',
    url: '/settings',
    method: 'GET',
    parent_id: 1,
    level: 2,
    order: 6,
    icon: 'setting',
    is_menu: MenuType.MENU,
    created_at: '2025-08-07T11:58:20',
    updated_at: '2025-08-07T11:58:20'
  },
  {
    id: 51,
    name: '修改配置',
    url: '/settings',
    method: 'PUT',
    parent_id: 50,
    level: 2,
    order: 1,
    icon: null,
    is_menu: MenuType.BUTTON,
    created_at: '2025-08-07T11:59:20',
    updated_at: '2025-08-07T11:59:20'
  }
]

// 构建权限树
function buildPermissionTree() {
  const tree: ApiPermission[] = []
  const permissionMap = new Map<number, ApiPermission & { children?: ApiPermission[] }>()
  
  // 先创建所有权限节点的映射
  permissions.forEach(permission => {
    const permWithChildren = { ...permission, children: [] }
    permissionMap.set(permission.id, permWithChildren)
  })
  
  // 构建树结构
  permissions.forEach(permission => {
    if (permission.parent_id === null) {
      tree.push(permissionMap.get(permission.id)!)
    } else {
      const parent = permissionMap.get(permission.parent_id)
      if (parent && parent.children) {
        parent.children.push(permissionMap.get(permission.id)!)
      }
    }
  })
  
  return tree
}

const permissionTree = buildPermissionTree()

// 根据角色ID获取对应的权限列表
function getPermissionsByRoleId(roleId: number): ApiPermission[] {
  // 找到对应的角色
  const role = roles.find(r => r.id === roleId)
  if (!role) return []
  
  // 获取该角色的所有权限ID
  const permissionIds = role.permissions
  
  // 根据权限ID获取权限详情
  return permissions.filter(p => permissionIds.includes(p.id))
}

// 获取用户的菜单权限
function getUserMenuPermissions(userId: number): ApiPermission[] {
  // 找到用户
  const user = users.find(u => u.id === userId)
  if (!user) return []
  
  // 获取用户角色的权限
  return getPermissionsByRoleId(user.role_id)
}

// 修复创建角色时的类型错误
function createRole(name: string, description: string, permission_ids: number[]) {
  const now = new Date().toISOString()
  return {
    id: roles.length > 0 ? Math.max(...roles.map(r => r.id)) + 1 : 1,
    name,
    description,
    permissions: permission_ids || [],
    permission_ids: permission_ids || [],
    permission_count: permission_ids ? permission_ids.length : 0,
    created_at: now,
    updated_at: now
  }
}

export default [
  // 认证相关API
  {
    url: '/api/v1/auth/login',
    method: 'post',
    response: ({ body }) => {
      const { login_name, password } = body
      
      // 简单的用户验证
      const user = users.find(u => u.login_name === login_name)
      
      if (!user) {
        return {
          code: 401,
          errorMsg: '用户名或密码错误',
          data: null
        }
      }
      
      // 实际项目中应该验证密码，这里简化处理
      
      return {
        code: 0,
        errorMsg: '',
        data: {
          access_token: `mock_token_${user.id}_${Date.now()}`,
          token_type: 'Bearer',
          user: {
            id: user.id,
            login_name: user.login_name,
            full_name: user.full_name,
            role_id: user.role_id,
            role_name: user.role_name,
            status: user.status,
            department: user.department
          }
        }
      }
    }
  },
  {
    url: '/api/v1/auth/register',
    method: 'post',
    response: ({ body }) => {
      const { login_name, full_name, password, confirm_password, department } = body
      
      // 验证密码
      if (password !== confirm_password) {
        return {
          code: 400,
          errorMsg: '两次密码输入不一致',
          data: null
        }
      }
      
      // 验证登录名唯一性
      if (users.find(u => u.login_name === login_name)) {
        return {
          code: 400,
          errorMsg: '登录名已存在',
          data: null
        }
      }
      
      // 创建新用户，默认为普通用户角色
      const now = new Date().toISOString()
      const newUser = {
        id: users.length > 0 ? Math.max(...users.map(u => u.id)) + 1 : 1,
        login_name,
        full_name,
        role_id: 2, // 默认为普通用户角色
        role_name: '普通用户',
        status: 0,
        department,
        created_at: now,
        updated_at: now
      }
      
      users.push(newUser)
      
      return {
        code: 0,
        errorMsg: '',
        data: newUser
      }
    }
  },
  {
    url: '/api/v1/auth/menu-permissions',
    method: 'get',
    response: ({ headers }) => {
      // 从请求头中获取token
      const token = headers.authorization || ''
      
      // 从token中提取用户ID（实际项目中应该解析JWT）
      const match = token.match(/mock_token_(\d+)_/)
      const userId = match ? parseInt(match[1]) : null
      
      if (!userId) {
        return {
          code: 401,
          errorMsg: '未授权',
          data: null
        }
      }
      
      // 获取用户的菜单权限
      const userPermissions = getUserMenuPermissions(userId)
      
      return {
        code: 0,
        errorMsg: '',
        data: userPermissions
      }
    }
  },
  {
    url: '/api/v1/auth/logout',
    method: 'post',
    response: () => {
      return {
        code: 0,
        errorMsg: '',
        data: { message: '退出登录成功' }
      }
    }
  },
  
  // 用户管理API
  {
    url: '/api/v1/users',
    method: 'get',
    response: ({ query }) => {
      const { page = 1, page_size = 10, keyword = '' } = query
      
      const filteredUsers = users.filter(user => 
        user.login_name.includes(keyword) || 
        user.full_name.includes(keyword) ||
        (user.department && user.department.includes(keyword))
      )
      
      const start = (page - 1) * page_size
      const end = start + parseInt(page_size)
      const pagedUsers = filteredUsers.slice(start, end)
      
      return {
        code: 0,
        errorMsg: '',
        data: pagedUsers,
        total: filteredUsers.length
      }
    }
  },
  {
    url: '/api/v1/users/:id',
    method: 'get',
    response: ({ query }) => {
      const { id } = query
      const user = users.find(u => u.id === parseInt(id))
      
      if (user) {
        return {
          code: 0,
          errorMsg: '',
          data: user
        }
      } else {
        return {
          code: 404,
          errorMsg: '用户不存在',
          data: null
        }
      }
    }
  },
  {
    url: '/api/v1/users',
    method: 'post',
    response: ({ body }) => {
      const { login_name, full_name, password, confirm_password, role_id, status = 0, department } = body
      
      // 验证密码
      if (password !== confirm_password) {
        return {
          code: 400,
          errorMsg: '两次密码输入不一致',
          data: null
        }
      }
      
      // 验证登录名唯一性
      if (users.find(u => u.login_name === login_name)) {
        return {
          code: 400,
          errorMsg: '登录名已存在',
          data: null
        }
      }
      
      // 验证角色存在
      if (!roles.find(r => r.id === role_id)) {
        return {
          code: 400,
          errorMsg: '角色不存在',
          data: null
        }
      }
      
      // 创建新用户
      const now = new Date().toISOString()
      const newUser = {
        id: users.length > 0 ? Math.max(...users.map(u => u.id)) + 1 : 1,
        login_name,
        full_name,
        role_id,
        role_name: roles.find(r => r.id === role_id)?.name || '',
        status,
        department,
        created_at: now,
        updated_at: now
      }
      
      users.push(newUser)
      
      return {
        code: 0,
        errorMsg: '',
        data: newUser
      }
    }
  },
  {
    url: '/api/v1/users/:id',
    method: 'put',
    response: ({ query, body }) => {
      const { id } = query
      const userIndex = users.findIndex(u => u.id === parseInt(id))
      
      if (userIndex === -1) {
        return {
          code: 404,
          errorMsg: '用户不存在',
          data: null
        }
      }
      
      const { full_name, role_id, status, department } = body
      
      // 验证角色存在
      if (role_id && !roles.find(r => r.id === role_id)) {
        return {
          code: 400,
          errorMsg: '角色不存在',
          data: null
        }
      }
      
      // 更新用户
      const updatedUser = {
        ...users[userIndex],
        full_name: full_name || users[userIndex].full_name,
        role_id: role_id || users[userIndex].role_id,
        role_name: role_id ? (roles.find(r => r.id === role_id)?.name || '') : users[userIndex].role_name,
        status: status !== undefined ? status : users[userIndex].status,
        department: department !== undefined ? department : users[userIndex].department,
        updated_at: new Date().toISOString()
      }
      
      users[userIndex] = updatedUser
      
      return {
        code: 0,
        errorMsg: '',
        data: updatedUser
      }
    }
  },
  {
    url: '/api/v1/users/:id',
    method: 'delete',
    response: ({ query }) => {
      const { id } = query
      const userIndex = users.findIndex(u => u.id === parseInt(id))
      
      if (userIndex === -1) {
        return {
          code: 404,
          errorMsg: '用户不存在',
          data: null
        }
      }
      
      users.splice(userIndex, 1)
      
      return {
        code: 0,
        errorMsg: '',
        data: { message: '用户删除成功' }
      }
    }
  },
  {
    url: '/api/v1/users/:id/change-password',
    method: 'post',
    response: ({ body }) => {
      const { old_password, new_password, confirm_password } = body
      
      // 验证密码
      if (new_password !== confirm_password) {
        return {
          code: 400,
          errorMsg: '两次密码输入不一致',
          data: null
        }
      }
      
      // 此处简化处理，不验证旧密码
      
      return {
        code: 0,
        errorMsg: '',
        data: { message: '密码修改成功' }
      }
    }
  },
  {
    url: '/api/v1/users/:id/reset-password',
    method: 'post',
    response: ({ body }) => {
      const { new_password, confirm_password } = body
      
      // 验证密码
      if (new_password !== confirm_password) {
        return {
          code: 400,
          errorMsg: '两次密码输入不一致',
          data: null
        }
      }
      
      return {
        code: 0,
        errorMsg: '',
        data: { message: '密码重置成功' }
      }
    }
  },
  
  // 角色管理API
  {
    url: '/api/v1/roles',
    method: 'get',
    response: ({ query }) => {
      const { page = 1, page_size = 10, keyword = '' } = query
      
      const filteredRoles = roles.filter(role => 
        role.name.includes(keyword) || 
        (role.description && role.description.includes(keyword))
      )
      
      const start = (page - 1) * page_size
      const end = start + parseInt(page_size)
      const pagedRoles = filteredRoles.slice(start, end).map(role => ({
        ...role,
        permission_count: role.permissions.length
      }))
      
      return {
        code: 0,
        errorMsg: '',
        data: pagedRoles,
        total: filteredRoles.length
      }
    }
  },
  {
    url: '/api/v1/roles/:id',
    method: 'get',
    response: ({ query }) => {
      const { id } = query
      const role = roles.find(r => r.id === parseInt(id))
      
      if (role) {
        return {
          code: 0,
          errorMsg: '',
          data: role
        }
      } else {
        return {
          code: 404,
          errorMsg: '角色不存在',
          data: null
        }
      }
    }
  },
  // 新增获取用户信息的API
  {
    url: '/api/v1/users/:id',
    method: 'get',
    response: ({ params }) => {
      const { id } = params
      const user = users.find(u => u.id === parseInt(id))
      
      if (user) {
        return {
          code: 0,
          errorMsg: '',
          data: user
        }
      } else {
        return {
          code: 404,
          errorMsg: '用户不存在',
          data: null
        }
      }
    }
  },
  // 获取角色信息及权限ID的API
  {
    url: '/api/v1/roles/:id',
    method: 'get',
    response: ({ params }) => {
      const { id } = params
      const role = roles.find(r => r.id === parseInt(id))
      
      if (role) {
        return {
          code: 0,
          errorMsg: '',
          data: {
            id: role.id,
            name: role.name,
            description: role.description,
            created_at: role.created_at,
            updated_at: role.updated_at,
            permission_ids: role.permission_ids || [],
            permission_count: role.permission_count || 0
          }
        }
      } else {
        return {
          code: 404,
          errorMsg: '角色不存在',
          data: null
        }
      }
    }
  },
  {
    url: '/api/v1/roles',
    method: 'post',
    response: ({ body }) => {
      const { name, description, permission_ids } = body
      
      // 验证角色名唯一性
      if (roles.find(r => r.name === name)) {
        return {
          code: 400,
          errorMsg: '角色名已存在',
          data: null
        }
      }
      
      // 验证权限ID存在
      if (permission_ids && !permission_ids.every(id => permissions.find(p => p.id === id))) {
        return {
          code: 400,
          errorMsg: '权限ID不存在',
          data: null
        }
      }
      
      // 创建新角色
      const newRole = createRole(name, description, permission_ids || [])
      
      roles.push(newRole)
      
      return {
        code: 0,
        errorMsg: '',
        data: newRole
      }
    }
  },
  {
    url: '/api/v1/roles/:id',
    method: 'put',
    response: ({ query, body }) => {
      const { id } = query
      const roleIndex = roles.findIndex(r => r.id === parseInt(id))
      
      if (roleIndex === -1) {
        return {
          code: 404,
          errorMsg: '角色不存在',
          data: null
        }
      }
      
      const { name, description, permission_ids } = body
      
      // 验证角色名唯一性
      if (name && name !== roles[roleIndex].name && roles.find(r => r.name === name)) {
        return {
          code: 400,
          errorMsg: '角色名已存在',
          data: null
        }
      }
      
      // 验证权限ID存在
      if (permission_ids && !permission_ids.every(id => permissions.find(p => p.id === id))) {
        return {
          code: 400,
          errorMsg: '权限ID不存在',
          data: null
        }
      }
      
      // 更新角色
      const updatedRole = {
        ...roles[roleIndex],
        name: name || roles[roleIndex].name,
        description: description !== undefined ? description : roles[roleIndex].description,
        permissions: permission_ids || roles[roleIndex].permissions,
        permission_ids: permission_ids || roles[roleIndex].permission_ids,
        permission_count: permission_ids ? permission_ids.length : roles[roleIndex].permission_count,
        updated_at: new Date().toISOString()
      }
      
      roles[roleIndex] = updatedRole
      
      return {
        code: 0,
        errorMsg: '',
        data: updatedRole
      }
    }
  },
  {
    url: '/api/v1/roles/:id',
    method: 'delete',
    response: ({ query }) => {
      const { id } = query
      const roleId = parseInt(id)
      const roleIndex = roles.findIndex(r => r.id === roleId)
      
      if (roleIndex === -1) {
        return {
          code: 404,
          errorMsg: '角色不存在',
          data: null
        }
      }
      
      // 检查是否有用户使用此角色
      if (users.find(u => u.role_id === roleId)) {
        return {
          code: 400,
          errorMsg: '该角色已被用户使用，无法删除',
          data: null
        }
      }
      
      roles.splice(roleIndex, 1)
      
      return {
        code: 0,
        errorMsg: '',
        data: { message: '角色删除成功' }
      }
    }
  },
  // 角色权限分配接口
  {
    url: '/api/v1/roles/:id/assign-permissions',
    method: 'post',
    response: ({ params, body }) => {
      const { id } = params
      const roleId = parseInt(id)
      const roleIndex = roles.findIndex(r => r.id === roleId)
      
      if (roleIndex === -1) {
        return {
          code: 404,
          errorMsg: '角色不存在',
          data: null
        }
      }
      
      const { permission_ids } = body
      
      // 验证权限ID存在
      if (!permission_ids.every(id => permissions.find(p => p.id === id))) {
        return {
          code: 400,
          errorMsg: '部分权限ID不存在',
          data: null
        }
      }
      
      // 更新角色权限
      roles[roleIndex] = {
        ...roles[roleIndex],
        permissions: permission_ids,
        permission_ids: permission_ids,
        permission_count: permission_ids.length,
        updated_at: new Date().toISOString()
      }
      
      return {
        code: 0,
        errorMsg: '',
        data: {
          id: roles[roleIndex].id,
          name: roles[roleIndex].name,
          description: roles[roleIndex].description,
          permission_ids: roles[roleIndex].permission_ids,
          permission_count: roles[roleIndex].permission_count,
          created_at: roles[roleIndex].created_at,
          updated_at: roles[roleIndex].updated_at
        }
      }
    }
  },
  
  // 权限管理API
  {
    url: '/api/v1/permissions',
    method: 'get',
    response: () => {
      return {
        code: 0,
        errorMsg: '',
        data: permissions
      }
    }
  },
  {
    url: '/api/v1/permissions/tree',
    method: 'get',
    response: () => {
      return {
        code: 0,
        errorMsg: '',
        data: permissionTree
      }
    }
  },
  {
    url: '/api/v1/permissions/:id',
    method: 'get',
    response: ({ query }) => {
      const { id } = query
      const permission = permissions.find(p => p.id === parseInt(id))
      
      if (permission) {
        return {
          code: 0,
          errorMsg: '',
          data: permission
        }
      } else {
        return {
          code: 404,
          errorMsg: '权限不存在',
          data: null
        }
      }
    }
  },
  {
    url: '/api/v1/permissions',
    method: 'post',
    response: ({ body }) => {
      const { name, url, method, parent_id, level, order = 0, icon, is_menu } = body
      
      // 验证父权限存在
      if (parent_id && !permissions.find(p => p.id === parent_id)) {
        return {
          code: 400,
          errorMsg: '父权限不存在',
          data: null
        }
      }
      
      // 创建新权限
      const now = new Date().toISOString()
      const newPermission = {
        id: permissions.length > 0 ? Math.max(...permissions.map(p => p.id)) + 1 : 1,
        name,
        url,
        method,
        parent_id,
        level,
        order,
        icon,
        is_menu,
        created_at: now,
        updated_at: now
      }
      
      permissions.push(newPermission)
      
      // 重建权限树
      buildPermissionTree()
      
      return {
        code: 0,
        errorMsg: '',
        data: newPermission
      }
    }
  },
  {
    url: '/api/v1/permissions/:id',
    method: 'put',
    response: ({ query, body }) => {
      const { id } = query
      const permissionIndex = permissions.findIndex(p => p.id === parseInt(id))
      
      if (permissionIndex === -1) {
        return {
          code: 404,
          errorMsg: '权限不存在',
          data: null
        }
      }
      
      const { name, url, method, parent_id, level, order, icon, is_menu } = body
      
      // 验证父权限存在且不形成循环引用
      if (parent_id) {
        if (!permissions.find(p => p.id === parent_id)) {
          return {
            code: 400,
            errorMsg: '父权限不存在',
            data: null
          }
        }
        
        // 防止循环引用
        if (parent_id === parseInt(id)) {
          return {
            code: 400,
            errorMsg: '不能将自己设为父权限',
            data: null
          }
        }
      }
      
      // 更新权限
      const updatedPermission = {
        ...permissions[permissionIndex],
        name: name || permissions[permissionIndex].name,
        url: url !== undefined ? url : permissions[permissionIndex].url,
        method: method !== undefined ? method : permissions[permissionIndex].method,
        parent_id: parent_id !== undefined ? parent_id : permissions[permissionIndex].parent_id,
        level: level !== undefined ? level : permissions[permissionIndex].level,
        order: order !== undefined ? order : permissions[permissionIndex].order,
        icon: icon !== undefined ? icon : permissions[permissionIndex].icon,
        is_menu: is_menu !== undefined ? is_menu : permissions[permissionIndex].is_menu,
        updated_at: new Date().toISOString()
      }
      
      permissions[permissionIndex] = updatedPermission
      
      // 重建权限树
      buildPermissionTree()
      
      return {
        code: 0,
        errorMsg: '',
        data: updatedPermission
      }
    }
  },
  {
    url: '/api/v1/permissions/:id',
    method: 'delete',
    response: ({ query }) => {
      const { id } = query
      const permissionId = parseInt(id)
      const permissionIndex = permissions.findIndex(p => p.id === permissionId)
      
      if (permissionIndex === -1) {
        return {
          code: 404,
          errorMsg: '权限不存在',
          data: null
        }
      }
      
      // 检查是否有子权限
      if (permissions.find(p => p.parent_id === permissionId)) {
        return {
          code: 400,
          errorMsg: '该权限有子权限，无法删除',
          data: null
        }
      }
      
      // 检查是否有角色使用此权限
      if (roles.find(r => r.permissions.includes(permissionId))) {
        return {
          code: 400,
          errorMsg: '该权限已被角色使用，无法删除',
          data: null
        }
      }
      
      permissions.splice(permissionIndex, 1)
      
      // 重建权限树
      buildPermissionTree()
      
      return {
        code: 0,
        errorMsg: '',
        data: { message: '权限删除成功' }
      }
    }
  }
] as MockMethod[]
